var setting = {
    data: {
        simpleData: {
            enable: true,
            idKey: "Id",
            pIdKey: "pId",
            rootPId: 0
        },
        key: {
            url:"nourl"
        }
    }
};
var setting_area = {
	    data: {
	        simpleData: {
	            enable: true,
	            idKey: "code",
	            pIdKey: "parentCode",
	            rootPId: 1
	        },
	        key: {
	            url:"nourl"
	        }
	    }
	};
var ztree;
var ztree_area;
/**
 * 展开树
 * @param treeId  
 */
function expand_ztree(treeId){
    var treeObj = $.fn.zTree.getZTreeObj(treeId);
    treeObj.expandAll(true);
}

/**
 * 收起树：只展开根节点下的一级节点
 * @param treeId
 */
function close_ztree(treeId){
    var treeObj = $.fn.zTree.getZTreeObj(treeId);
    var nodes = treeObj.transformToArray(treeObj.getNodes());
    var nodeLength = nodes.length;
    for (var i = 0; i < nodeLength; i++) {
        if (nodes[i].id == '0') {
            //根节点：展开
            treeObj.expandNode(nodes[i], true, true, false);
        } else {
            //非根节点：收起
            treeObj.expandNode(nodes[i], false, true, false);
        }
    }
}

/**
 * 搜索树，高亮显示并展示【模糊匹配搜索条件的节点s】
 * @param treeId
 * @param searchConditionId 文本框的id
 */
function search_ztree(treeId, searchConditionId){
	searchByFlag_ztree(treeId, searchConditionId, "");
}

/**
 * 搜索树，高亮显示并展示【模糊匹配搜索条件的节点s】
 * @param treeId
 * @param searchConditionId		搜索条件Id
 * @param flag 					需要高亮显示的节点标识
 */
function searchByFlag_ztree(treeId, searchConditionId, flag){
	//<1>.搜索条件
	var searchCondition = $('#' + searchConditionId).val();
	//<2>.得到模糊匹配搜索条件的节点数组集合
	var highlightNodes = new Array();
	if (searchCondition != "") {
		var treeObj = $.fn.zTree.getZTreeObj(treeId);
		highlightNodes = treeObj.getNodesByParamFuzzy("name", searchCondition, null);
	}
	//<3>.高亮显示并展示【指定节点s】
	highlightAndExpand_ztree(treeId, highlightNodes, flag);
}

/**
 * 高亮显示并展示【指定节点s】
 * @param treeId
 * @param highlightNodes 需要高亮显示的节点数组
 * @param flag			 需要高亮显示的节点标识
 */
function highlightAndExpand_ztree(treeId, highlightNodes, flag){
	var treeObj = $.fn.zTree.getZTreeObj(treeId);
	//<1>. 先把全部节点更新为普通样式
	var treeNodes = treeObj.transformToArray(treeObj.getNodes());
	for (var i = 0; i < treeNodes.length; i++) {
		treeNodes[i].highlight = false;
		treeObj.updateNode(treeNodes[i]);
	}
	
	//<2>.收起树, 只展开根节点下的一级节点
	close_ztree(treeId);
	//<3>.把指定节点的样式更新为高亮显示，并展开
	if (highlightNodes != null) {
		for (var i = 0; i < highlightNodes.length; i++) {
			if (flag != null && flag != "") {
				if (highlightNodes[i].flag == flag) {
					//高亮显示节点，并展开
					highlightNodes[i].highlight = true;
					treeObj.updateNode(highlightNodes[i]);
					//高亮显示节点的父节点的父节点....直到根节点，并展示
					var parentNode = highlightNodes[i].getParentNode();
					var parentNodes = getParentNodes_ztree(treeId, parentNode);
					treeObj.expandNode(parentNodes, true, false, true);
					treeObj.expandNode(parentNode, true, false, true);
				}
			} else {
				//高亮显示节点，并展开
				highlightNodes[i].highlight = true;
				treeObj.updateNode(highlightNodes[i]);
				//高亮显示节点的父节点的父节点....直到根节点，并展示
				var parentNode = highlightNodes[i].getParentNode();
				var parentNodes = getParentNodes_ztree(treeId, parentNode);
				treeObj.expandNode(parentNodes, true, false, true);
				treeObj.expandNode(parentNode, true, false, true);
			}
		}
	}
}

/**
 * 递归得到指定节点的父节点的父节点....直到根节点
 */
function getParentNodes_ztree(treeId, node){
	if (node != null) {
		var treeObj = $.fn.zTree.getZTreeObj(treeId);
		var parentNode = node.getParentNode();
		return getParentNodes_ztree(treeId, parentNode);
	} else {
		return node;
	}
}

/**
 * 设置树节点字体样式
 */
function setFontCss_ztree(treeId, treeNode) {
	if (treeNode.id == 0) {
		//根节点
		return {color:"#333", "font-weight":"bold"};
	} else if (treeNode.isParent == false){
		//叶子节点
		return (!!treeNode.highlight) ? {color:"#ff0000", "font-weight":"bold"} : {color:"#660099", "font-weight":"normal"};
	} else {
		//父节点
		return (!!treeNode.highlight) ? {color:"#ff0000", "font-weight":"bold"} : {color:"#333", "font-weight":"normal"};
	}
}
var vm = new Vue({
    el:'#rrapp',
    data:{
        showList: true,
        title: null,
        agent:{
        /*    parentName:null,
            parentId:0,
            regionName:null,
            parentCode:1,
            type:0,
            orderNum:0*/
        }
    },
    methods: {
        getDept: function(){
            //加载组织树
            $.get(baseURL + "sys/agent/deptSelect", function(r){
                ztree = $.fn.zTree.init($("#deptTree"), setting, r.deptList);
                var node = ztree.getNodeByParam("Id", 1);
                //console.log(node);
                ztree.selectNode(node);
                vm.agent.parentName = node.name;
                $("#parentName").val(node.name);
                
            })
        },
        getDept_update: function(id){
            //加载组织树
            $.get(baseURL + "sys/agent/deptSelect", function(r){
                ztree = $.fn.zTree.init($("#deptTree"), setting, r.deptList);
                var node = ztree.getNodeByParam("Id", id);
                ztree.selectNode(node);
                vm.agent.parentName = node.name;
                $("#parentName").val(name);
                
            })
        },
        getArea: function(){
            //加载组织树
            $.get(baseURL + "sys/agent/areaSelect", function(r){
            	ztree_area = $.fn.zTree.init($("#areaTree"), setting_area, r.areaList);
            	var node = ztree_area.getNodeByParam("code",100000000000);
                ztree_area.selectNode(node);
                vm.agent.regionName = node.name;
                $("#regionName").val(node.name);
                
            })
        },
        getArea_update: function(code){
            //加载组织树
            $.get(baseURL + "sys/agent/areaSelect", function(r){
            	ztree_area = $.fn.zTree.init($("#areaTree"), setting_area, r.areaList);
            	var node = ztree_area.getNodeByParam("code",code);
                ztree_area.selectNode(node);
                vm.agent.regionName = node.name;
                $("#regionName").val(node.name);
                
            })
        },
        add: function(){
            vm.showList = false;
            vm.title = "新增";
            vm.getArea();
            vm.getDept();
            $.get(baseURL + "sys/agent/info", function(r){
                vm.agent = {parentId:r.selfId,orderNum:0,type:6,del_flag:0};
            });
                
        },
        update: function () {
        	vm.getArea();
            
            var deptId = getDeptId();
            if(deptId == null){
                return ;
            }
            
            $.get(baseURL + "sys/agent/info/"+deptId, function(r){
                vm.showList = false;
                vm.title = "修改";
                vm.agent = r.agent;
                //console.log(r);
                vm.getDept_update(r.agent.parent_id);
                vm.getArea_update(r.agent.code);
                vm.agent.orderNum =r.agent.order_num;
                
            });
        },
        del: function () {
            var deptId = getDeptId();
            if(deptId == null){
                return ;
            }
           // console.log(deptId);
            confirm('确定要删除选中的记录？', function(){
                $.ajax({
                    type: "POST",
                    url: baseURL + "sys/agent/delete",
                    contentType: "application/json",
                    data: JSON.stringify(deptId),
                    success: function(r){
                        if(r.code === 0){
                            alert('操作成功', function(){
                                vm.reload();
                            });
                        }else{
                            alert(r.msg);
                        }
                    }
                });
            });
        },
        saveOrUpdate: function (event) {
            var url = vm.agent.deptId == null ? "sys/agent/save" : "sys/agent/update";
            $.ajax({
                type: "POST",
                url: baseURL + url,
                contentType: "application/json",
                data: JSON.stringify(vm.agent),
                success: function(r){
                    if(r.code === 0){
                        alert('操作成功', function(){
                            vm.reload();
                        });
                    }else{
                        alert(r.msg);
                    }
                }
            });
        },
        deptTree: function(){
            layer.open({
                type: 1,
                offset: '50px',
                skin: 'layui-layer-molv',
                title: "选择组织",
                area: ['300px', '450px'],
                shade: 0,
                shadeClose: false,
                content: jQuery("#deptLayer"),
                btn: ['确定', '取消'],
                btn1: function (index) {
                    var node = ztree.getSelectedNodes();
                    //选择上级组织
                    vm.agent.parentId = node[0].Id;
                    vm.agent.parentName = node[0].name;
                    $("#parentName").val(node[0].name);
                    layer.close(index);
                }
            });
        },
        areaTree: function(){
            layer.open({
                type: 1,
                offset: '50px',
                skin: 'layui-layer-molv',
                title: "选择区域",
                area: ['300px', '650px'],
                shade: 0,
                shadeClose: false,
                content: jQuery("#areaLayer"),
                btn: ['确定', '取消'],
                btn1: function (index) {
                    var node = ztree_area.getSelectedNodes();
                    //选择上级区域
                    vm.agent.parentCode = node[0].code;
                    vm.agent.regionId = node[0].id;
                    vm.agent.regionName = node[0].name;
                    getParentNode(node[0]);
                    $("#regionName").val(arr.reverse().toString().replace(/,/g,"-"));
                    layer.close(index);
                    arr.length = 0;
                }
            });
        },
        reload: function () {
            vm.showList = true;
            Dept.table.refresh();
        }
    }
});




//递归父节点
var arr = new Array();
function getParentNode(node){
	if (node==null || node.parentCode==1) {
		return ;
	}
	else
	{
		arr.push(node.name);
		getParentNode(node.getParentNode());
	}
	
}


var Dept = {
    id: "deptTable",
    table: null,
    layerIndex: -1
};

/**
 * 初始化表格的列
 */
Dept.initColumn = function () {
    var columns = [
        {field: 'selectItem', radio: true},
        {title: '组织ID', field: 'dept_id',hidden:true, visible: false, align: 'center', valign: 'middle', width: '80px'},
        {title: '组织名称', field: 'name', align: 'center', valign: 'middle', sortable: true, width: '180px'},
        {title: '上级组织', field: 'parent_id', align: 'center', valign: 'middle', sortable: true, width: '100px'},
        {title: '所在 区域', field: 'regionName', align: 'center', valign: 'middle', sortable: true, width: '100px'},
        {title: '详细地址', field: 'address', align: 'center', valign: 'middle', sortable: true, width: '100px'},
        {title: '联系人姓名', field: 'linkname', align: 'center', valign: 'middle', sortable: true, width: '100px'},
        {title: '职务', field: 'duty', align: 'center', valign: 'middle', sortable: true, width: '100px'},
        {title: '手机号码', field: 'mobileNO', align: 'center', valign: 'middle', sortable: true, width: '100px'}]
    return columns;
};


function getDeptId () {
    var selected = $('#deptTable').bootstrapTreeTable('getSelections');
    if (selected.length == 0) {
        alert("请选择一条记录");
        return false;
    } else {
        return selected[0].id;
    }
}


$(function () {
    $.get(baseURL + "sys/agent/info", function(r){
        var colunms = Dept.initColumn();
        var table = new TreeTable(Dept.id, baseURL + "sys/agent/list", colunms);
        table.setRootCodeValue(r.Id);
        table.setExpandColumn(2);
        table.setIdField("deptId");
        table.setCodeField("deptId");
        table.setParentCodeField("pId");
        table.setExpandAll(false);
        table.init();
        Dept.table = table;
    });
});
